package web.language.helper

class DictionaryController {

    def index() { }

    def list() {
        List<Dictionary> dics = Dictionary.findAll()
        setUserWorkDic(dics)
        List dir = ['English', 'Русский']
        List keys = [true, false]
        [ dics : dics, directionList : dir, dirVal : session.getValue("direction"), keys : keys]
    }

    def setUserWorkDic(dics) {
        def userDics = WorkDictionary.findByUser(session.user.name)
        dics.each {web.language.helper.Dictionary dic ->
            def workDic = (userDics != null) ? userDics.findWhere(dictionary: dic) : null
            dic.setWork(workDic != null)
        }
    }

    def modify() {
        def dic = Dictionary.findById(params["id"])
        redirect(controller:"entry", action: "list", params: [id: params.get("id"), dicName: dic.name])
    }

    def learn() {
        redirect controller: "learn", action: "start"
    }

    def create() {
        [propertyName: new Dictionary(params)]
    }

    def save() {
        Dictionary newDic = new Dictionary(params)
        newDic.setCreator(session.user.name)
        newDic.setId("2")
        newDic.save(flash: true)

        redirect action: "list"
    }

    def applyWork() {
        Dictionary dic = Dictionary.findById(params.id)
        Boolean work = params.workDic.toBoolean()

        dic.setWork(work)
        dic.save()

        WorkDictionary workDic = WorkDictionary.findByUserAndDictionary(session.user.name, dic)
        if (work) {
            if (!workDic) {
                new WorkDictionary(dictionary: dic, user: session.user.name).save()
            }
        } else if (workDic) {
            workDic.delete()
        }

        redirect action: "list"
    }

    static Collection<Entry> getForLearn(Dictionary dic, User currentUser) {
        List<Integer> ids = new ArrayList<Integer>()

        dic.entries.each {entry ->
            def stat = entry.statistic.find { stat -> stat.user == currentUser && (stat.right - stat.wrong) < 2}
            if (stat == null) {
                ids.add entry.id
            }
        }
        ids as Collection<Entry>
    }

    def applyDirection() {
        session.putValue("direction", params.dir.toBoolean())
    }
}
